<template>

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="流程分类" prop="category">
        <el-select
          v-model="queryParams.category"
          placeholder="请选择流程分类"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="category in categoryList"
            :key="category.code"
            :label="category.name"
            :value="category.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="流程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入流程名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="openModelForm('create')">
          <Icon class="mr-5px" icon="ep:plus" />
          新建
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="tableRef"
      :data="list"
      row-key="id"
    >
      <el-table-column align="center" label="流程名称" prop="name" width="150" />
      <el-table-column align="center" label="流程标识" prop="key" width="100" />
      <el-table-column align="center" label="流程分类" prop="category" width="100" />
      <el-table-column align="center" label="流程类型" prop="type" min-width="120">
        <template #default="{ row }">
          <dict-tag :value="row.type" :type="DICT_TYPE.BPM_MODEL_TYPE" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="可见范围" prop="startUserIds" min-width="150">
        <template #default="{ row }">
          <el-text v-if="!row.startUsers?.length && !row.startDepts?.length"> 全部可见 </el-text>
          <el-text v-else-if="row.startUsers.length === 1">
            {{ row.startUsers[0].nickname }}
          </el-text>
          <el-text v-else-if="row.startDepts?.length === 1">
            {{ row.startDepts[0].name }}
          </el-text>
          <el-text v-else-if="row.startDepts?.length > 1">
            <el-tooltip
              class="box-item"
              effect="dark"
              placement="top"
              :content="row.startDepts.map((dept: any) => dept.name).join('、')"
            >
              {{ row.startDepts[0].name }}等 {{ row.startDepts.length }} 个部门可见
            </el-tooltip>
          </el-text>
          <el-text v-else>
            <el-tooltip
              class="box-item"
              effect="dark"
              placement="top"
              :content="row.startUsers.map((user: any) => user.nickname).join('、')"
            >
              {{ row.startUsers[0].nickname }}等 {{ row.startUsers.length }} 人可见
            </el-tooltip>
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" label="表单信息" prop="formType" width="150">
        <template #default="scope">
          <el-button
            v-if="scope.row.formType === BpmModelFormType.NORMAL"
            type="primary"
            link
            @click="handleFormDetail(scope.row)"
          >
            <span>{{ scope.row.formName }}</span>
          </el-button>
          <el-button
            v-else-if="scope.row.formType === BpmModelFormType.CUSTOM"
            type="primary"
            link
            @click="handleFormDetail(scope.row)"
          >
            <span>{{ scope.row.formCustomCreatePath }}</span>
          </el-button>
          <label v-else>暂无表单</label>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布状态" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.processDefinition">
            已发布
          </el-tag>
          <el-tag v-else type="info">未发布</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="流程版本" width="150">
        <template #default="scope">
          <el-tag type="warning" v-if="scope.row.processDefinition">
            v{{ scope.row.processDefinition?.version }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后发布时间" prop="deploymentTime" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.processDefinition?.deploymentTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openModelForm('update', scope.row.id)"
            v-if="hasPermiUpdate"
            :disabled="!isManagerUser(scope.row)"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            @click="openModelForm('copy', scope.row.id)"
            v-if="hasPermiUpdate"
            :disabled="!isManagerUser(scope.row)"
          >
            复制
          </el-button>
          <el-button
            link
            class="!ml-5px"
            type="primary"
            @click="handleDeploy(scope.row)"
            v-if="hasPermiDeploy"
            :disabled="!isManagerUser(scope.row)"
          >
            发布
          </el-button>
          <el-dropdown
            class="!align-middle ml-5px"
            @command="(command) => handleModelCommand(command, scope.row)"
            v-if="hasPermiMore"
          >
            <el-button type="primary" link>更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="handleDefinitionOpen" v-if="hasPermiPdQuery">
                  版本管理
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleReport"
                  v-if="
                      checkPermi(['bpm:process-instance:manager-query']) &&
                      scope.row.processDefinition
                    "
                  :disabled="!isManagerUser(scope.row)"
                >
                  报表
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleChangeState"
                  v-if="false && hasPermiUpdate && scope.row.processDefinition"
                  :disabled="!isManagerUser(scope.row)"
                >
                  {{ scope.row.processDefinition.suspensionState === 1 ? '停用' : '启用' }}
                </el-dropdown-item>
                <el-dropdown-item
                  type="danger"
                  command="handleClean"
                  v-if="checkPermi(['bpm:model:clean'])"
                  :disabled="!isManagerUser(scope.row)"
                >
                  清理
                </el-dropdown-item>
                <el-dropdown-item
                  type="danger"
                  command="handleDelete"
                  v-if="hasPermiDelete"
                  :disabled="!isManagerUser(scope.row)"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />

    <DefinitionVersion ref="definitionDrawerRef" @close="handleDefinitionClose" />
  </ContentWrap>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { BpmModelFormType } from "@/utils/constants";
import { checkPermi } from "@/utils/permission";
import * as ModelApi from "@/api/bpm/model";
import { CategoryApi } from "@/api/bpm/category";
import * as FormApi from "@/api/bpm/form";
import { setConfAndFields2 } from "@/utils/formCreate";
import { useUserStoreWithOut } from "@/store/modules/user";

import DefinitionVersion from "./definition/index.vue";

const categoryList = ref([]) // 按照 category 分组的数据
const message = useMessage() // 消息弹窗
const router = useRouter() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由
const userStore = useUserStoreWithOut() // 用户信息缓存

const definitionDrawerRef = ref(null)
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  category: undefined,
})
const queryFormRef = ref() // 搜索的表单

/** 权限校验：通过 computed 解决列表的卡顿问题 */
const hasPermiUpdate = computed(() => {
  return checkPermi(['bpm:model:update'])
})
const hasPermiDelete = computed(() => {
  return checkPermi(['bpm:model:delete'])
})
const hasPermiDeploy = computed(() => {
  return checkPermi(['bpm:model:deploy'])
})
const hasPermiMore = computed(() => {
  return checkPermi(['bpm:process-definition:query', 'bpm:model:update', 'bpm:model:delete'])
})
const hasPermiPdQuery = computed(() => {
  return checkPermi(['bpm:process-definition:query'])
})

/** 判断是否可以操作 */
const isManagerUser = (row: any) => {
  const userId = userStore.getUser.id
  return row.managerUserIds && row.managerUserIds.includes(userId)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 查询模型 + 分裂的列表
    const data = await ModelApi.getModelList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 流程表单的详情按钮操作 */
const formDetailVisible = ref(false)
const formDetailPreview = ref({
  rule: [],
  option: {}
})
const handleFormDetail = async (row: any) => {
  if (row.formType == BpmModelFormType.NORMAL) {
    // 设置表单
    const data = await FormApi.getForm(row.formId)
    setConfAndFields2(formDetailPreview, data.conf, data.fields)
    // 弹窗打开
    formDetailVisible.value = true
  } else {
    await push({
      path: row.formCustomCreatePath
    })
  }
}

/** 添加/修改/复制流程模型弹窗 */
const openModelForm = async (type: string, id?: number) => {
  if (type === 'create') {
    await push({ name: 'BpmModelCreate' })
  } else {
    await push({
      name: 'BpmModelUpdate',
      params: { id, type }
    })
  }
}

/** 发布流程 */
const handleDeploy = async (row: any) => {
  try {
    await message.confirm('是否确认发布该流程？')
    // 发起部署
    await ModelApi.deployModel(row.id)
    message.success(t('发布成功'))
    getList()
  } catch {}
}

/** '更多'操作按钮 */
const handleModelCommand = (command: string, row: any) => {
  switch (command) {
    case 'handleDefinitionOpen':
      handleDefinitionOpen(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
    case 'handleChangeState':
      handleChangeState(row)
      break
    case 'handleClean':
      handleClean(row)
      break
    case 'handleReport':
      router.push({
        name: 'BpmProcessInstanceReport',
        query: {
          processDefinitionId: row.processDefinition.id,
          processDefinitionKey: row.key
        }
      })
      break
    default:
      break
  }
}

// 版本管理关闭回调 - 在这里刷新模型列表
const handleDefinitionClose = () => {
  console.log('版本管理已关闭，刷新模型列表')
  // 调用你的模型列表刷新方法
  getList()
}

/** 跳转到指定流程定义列表 */
const handleDefinitionOpen = (row: any) => {
  definitionDrawerRef.value.open({
    modelId: row.id,
    modelKey: row.key,
    processDefinitionId: row.processDefinition?.id
  })
  // push({
  //   name: 'BpmProcessDefinition',
  //   query: {
  //     key: row.key
  //   }
  // })
}

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ModelApi.deleteModel(row.id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    getList()
  } catch {}
}

/** 清理按钮操作 */
const handleClean = async (row: any) => {
  try {
    // 清理的二次确认
    await message.confirm('是否确认清理流程名字为"' + row.name + '"的数据项?')
    // 发起清理
    await ModelApi.cleanModel(row.id)
    message.success('清理成功')
    // 刷新列表
    getList()
  } catch {}
}

/** 更新状态操作 */
const handleChangeState = async (row: any) => {
  const state = row.processDefinition.suspensionState
  const newState = state === 1 ? 2 : 1
  try {
    // 修改状态的二次确认
    const id = row.id
    const statusState = state === 1 ? '停用' : '启用'
    const content = '是否确认' + statusState + '流程名字为"' + row.name + '"的数据项?'
    await message.confirm(content)
    // 发起修改状态
    await ModelApi.updateModelState(id, newState)
    message.success(statusState + '成功')
    // 刷新列表
    getList()
  } catch {}
}

watch(
  () => router.currentRoute.value,
  () => {
    getList()
  }
)

/** 初始化 **/
onMounted(async () => {
  categoryList.value = await CategoryApi.getCategorySimpleList()
  await getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}
</style>
